package sortAlgorithm;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * CustomSortString
 *
 * @author <a href="zhaoyingling12@163.com">Zhao Simon</a>
 * @description: https://leetcode.cn/problems/custom-sort-string/ 791. 自定义字符串排序
 * @date 2023/2/28
 **/
public class CustomSortString {

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.customSortString("cba", "abcddddf"));
    }

    private static class Solution {
        public String customSortString(String order, String s) {
            Map<Character, Integer> charOrderMap = new HashMap<>();
            for (int i = 0; i < order.length(); i++) {
                charOrderMap.put(order.charAt(i), i + 1);
            }
            Character[] charArray = new Character[s.length()];
            int index = 0;
            for (int j = 0; j < s.length(); j++) {
                charArray[index++] = s.charAt(j);
            }
            Comparator<Character> comparator = new Comparator<Character>() {
                public int compare(Character o1, Character o2) {

                    Integer order1 = charOrderMap.get(o1), order2 = charOrderMap.get(o2);
                    // 随便返回一个
                    if (order1 == null && order2 == null) {
                        return 0;
                    }
                    // order2 order1
                    if (order1 == null && order2 != null) {
                        return 1;
                    }
                    // order1 order2
                    if (order1 != null && order2 == null) {
                        return -1;
                    }
                    return order1 < order2 ? -1 : order1 == order2 ? 0 : 1;
                }
            };
            Arrays.sort(charArray, comparator);
            return toString(charArray);
        }

        private String toString(Character[] characters) {
            StringBuilder builder = new StringBuilder();
            for (Character character : characters) {
                if (character != null) {
                    builder.append(character);
                }
            }
            return builder.toString();
        }
    }
}
